package com.xm9m.ibczy.dsp.http.bhttp.http;

import com.xm9m.ibczy.dsp.http.bhttp.utils.IOUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by baichuan on 2016/11/25.
 */

public class BCPostRequest implements Runnable {
    private String url;
    private BCHttpListener listener;
    private HttpURLConnection http;
    private byte[] data;
    private int stateCode;

    private byte[] bys;
    private Map<String, String> map;
    private String tKey;

    public BCPostRequest(String url) {
        if (url == null || url.trim().length() == 0)
            throw new IllegalArgumentException("url is null");
        this.url = url;
    }


    public BCPostRequest withBody(byte[] body) {
        this.bys = body;
        return this;
    }


    public BCPostRequest withListener(BCHttpListener listener) {
        this.listener = listener;
        return this;
    }

    @Override
    public void run() {
        try {
            URL uurl = new URL(url);
            http = (HttpURLConnection) uurl.openConnection();
            http.setDoInput(true);
            http.setDoOutput(true);
            if (null != bys) {
                OutputStream hout = http.getOutputStream();
                hout.write(bys);
                hout.flush();
            }
            if (null != map) {
                Iterator<String> iterator = map.keySet().iterator();
                while (iterator.hasNext()) {
                    tKey = iterator.next();
                    http.setRequestProperty(tKey, map.get(tKey));
                }
            }

            http.connect();
            data = IOUtils.getFromInput(http.getInputStream());
            stateCode = http.getResponseCode();

            if (null != listener) {
                if (stateCode == 200) {
                    listener.onSuccess(stateCode, data);
                } else {
                    listener.onError(stateCode, http.getResponseMessage());
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
